import 'package:flutter/material.dart';
import 'package:ft_reader/beans/category_item_bean.dart';
import 'package:ft_reader/blocs/categary_bloc.dart';
import 'package:ft_reader/widgets/category_item.dart';
import 'package:ft_reader/widgets/reload_widget.dart';
import 'package:ft_reader/widgets/loading_widget.dart';

// 类别
class CategoryPage extends StatefulWidget {

  @override
  _CategoryPage createState() => _CategoryPage();

}

class _CategoryPage extends State<StatefulWidget>
  with AutomaticKeepAliveClientMixin{

  CategoryBloc _categoryBloc = new CategoryBloc();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _categoryBloc.fetchCategoryItems();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      child: StreamBuilder(
        stream: _categoryBloc.categoryItems,
        builder: (BuildContext context, AsyncSnapshot<List<CategoryItemBean>> content) {
          if (content.hasData) {
            return Container(
              padding: EdgeInsets.all(20),
              child: GridView.count(
                crossAxisCount: 3,
                shrinkWrap: true,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
                childAspectRatio: 2 / 3, // 宽高比
                children: content.data.map((data) {
                  return CatedoryItem(context,
                      content.data.indexOf(data), data);
                }).toList(),
              ),
            );
          } else if (content.data == null && content.connectionState == ConnectionState.active) {
            return ReloadWidget(refreshCallback: _refresh,);
          } else {
            return LoadingWidget(
              color: Theme.of(context).primaryColor,
            );
          }
        },
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _categoryBloc.dispose();
  }

  Future<void> _refresh() {
    _categoryBloc.fetchCategoryItems();
  }

}